<template>
    <div>
        <el-dialog title="扫描二维码显示" :width="dialogWidth + 'px'" :visible.sync="show" :close-on-click-modal="false" @opened="showCode" @close="cancelQr">
            <div ref="qrcode" class="codeStyle"></div>
        </el-dialog>
    </div>
</template>
<script>
import QRCode from 'qrcodejs2'
export default {
    props: {
        dialogVisible: { type: Boolean }, // 弹窗显示
        dialogWidth: { type: Number, default: 400 }, // 弹窗宽度
        paths: { type: String, default: '' } // 文件下载路径
    },
    data() {
        return {
            showDialog: false
        }
    },  
    computed: {
        show: {
            get() {
                this.showDialog = this.dialogVisible;
                return this.showDialog;
            },
            set(val) {
                return this.$emit('cancelQr', val)
            }
        }
    },
    methods: {
        /** 显示二维码图片 */
        showCode() {
            this.creatCode();
        },
        /** 转换二维码 */
        creatCode() {
            // 清除上一张二维码的缓存
            this.$refs.qrcode.innerHTML = ''
            let qrcode = new QRCode(this.$refs.qrcode, {
                width: 200,
                height: 200,
                render: 'canvas',
                correctLevel: QRCode.CorrectLevel.H
            })
            // 对所需要的内容进行转码
            qrcode.makeCode(this.paths)
            let canvas = document.querySelector('canvas')
            var pic = canvas.toDataURL('image/png')
            canvas.outerHTML = '<img alt="Scan me!" src=' + pic+ ' style="display: block;">'
            qrcode.clear()
        },
        /** 弹窗关闭 */
        cancelQr() {
            this.showDialog = false;
        }
    }
}
</script>
<style scoped>
.codeStyle{
    margin: 20px;
    background: #9093993d;
    width: 200px;
    height: 200px;
    margin: auto;
    margin-bottom: 30px;
}
</style>